package com.aizuda.redislock;

import com.aizuda.common.toolkit.RequestUtils;
import com.aizuda.redislock.annotation.DistributedLimit;
import com.aizuda.redislock.strategy.IDistributedKeyBuilderStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author zhongjiahua
 * @date 2021-11-28
 * @Description: 自定义key生成粗略
 */
@Component
@Slf4j
public class KeyBuilderStrategy implements IDistributedKeyBuilderStrategy {

    @Override
    public boolean support(Method method, String classMethodName, DistributedLimit distributedLimit, String distributedLimitKey) {
        // 只对controller访问控制
        return AnnotatedElementUtils.hasAnnotation(method, RequestMapping.class)
                && "/custom-key-lock-test".equals(RequestUtils.getRequest().getRequestURI());
    }

    @Override
    public String buildKey(Method method, String classMethodName, DistributedLimit distributedLimit, String distributedLimitKey) {
        HttpServletRequest request = RequestUtils.getRequest();
        String uri = request.getRequestURI();

        // 用户唯一标识
        String username = "zhangsan";
        return username + ":" + uri + ":" + distributedLimitKey;
    }
}
